import Flutter
import UIKit

public class SwiftLeafRustPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "leaf_rust", binaryMessenger: registrar.messenger())
    let instance = SwiftLeafRustPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
      case "leaf_run":
        let arguments = (call.arguments ?? [:]) as! [String: Any]
        let rtId = arguments["rtId"] as! UInt16
        let confPath = arguments["configPath"] as! String
        let globalQueue = DispatchQueue.global()
        globalQueue.async {
          leaf_run(rtId, confPath)
        }
        DispatchQueue.main.async {
          result(0)
        }
      case "getPlatformVersion":
        result("iOS " + UIDevice.current.systemVersion);
      default:
        print(#function, #line, call.method, call.arguments as Any)
        result(FlutterMethodNotImplemented)
    }
  }

  public func dummyMethodToEnforceBundling() {
    // dummy calls to prevent tree shaking
    leaf_run(1, "abc.conf")
    leaf_run_with_options(1, "abc.conf", false, false, false, 1, 2000)
    leaf_run_with_config_string(1, "")
    leaf_reload(1);
    leaf_shutdown(1);
    leaf_test_config("abc.conf");
  }
}
